<?php

// +----------------------------------------------------------------------
// | Copyright (c) 2015－03－21 http://www.cencn.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: 林群伟  <56583965@qq.com> <http://www.xzqly.com>
// +----------------------------------------------------------------------

namespace Common\Model;

use Think\Model;

/**
 * 菜单模型
 * @author 林群伟
 */
class MenuModel extends Model {

    protected $_validate = array(
        array('title', 'require', '标题名称是必须的'), //默认情况下用正则进行验证
        array('class_icon', 'require', '小图标是必须的'), //默认情况下用正则进行验证
        array('url', 'require', 'url必须填写'), //默认情况下用正则进行验证
    );

    public function getReturnNode($tree=TRUE) {
        static $tree_nodes = array();
        if ( $tree && !empty($tree_nodes[(int)$tree]) ) {
            return $tree_nodes[$tree];
        }
        if((int)$tree){
            $list = M('Menu')->field('id,pid,title,url,tip,hide')->order('sort asc')->select();
            foreach ($list as $key => $value) {
                if( stripos($value['url'],MODULE_NAME)!==0 ){
                    $list[$key]['url'] = MODULE_NAME.'/'.$value['url'];
                }
            }
            $nodes = list_to_tree($list,$pk='id',$pid='pid',$child='operator',$root=0);
            foreach ($nodes as $key => $value) {
                if(!empty($value['operator'])){
                    $nodes[$key]['child'] = $value['operator'];
                    unset($nodes[$key]['operator']);
                }
            }
        } else {
            $nodes = $this->field('title,url,tip,pid')->order('sort asc')->select();
            foreach ($nodes as $key => $value) {
                if (stripos($value['url'], MODULE_NAME) !== 0) {
                    $nodes[$key]['url'] = MODULE_NAME . '/' . $value['url'];
                }
            }
        }
        return $nodes;
    }

    //获取树的根到子节点的路径
    public function getPath($id) {
        $path = array();
        $nav = $this->where("id={$id}")->field('id,pid,title')->find();
        $path[] = $nav;
        if ($nav['pid'] > 0) {
            $path = array_merge($this->getPath($nav['pid']), $path);
        }
        return $path;
    }

}
